package com.xhs.service;

import com.xhs.entity.Content;
import com.xhs.entity.Like;
import com.xhs.entity.User;
import com.xhs.repository.ContentRepository;
import com.xhs.repository.LikeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * 点赞服务
 */
@Service
@Transactional
public class LikeService {
    
    @Autowired
    private LikeRepository likeRepository;
    
    @Autowired
    private ContentRepository contentRepository;
    
    /**
     * 点赞或取消点赞
     */
    public boolean toggleLike(Long contentId, User user) {
        Content content = contentRepository.findById(contentId)
                .orElseThrow(() -> new RuntimeException("内容不存在"));
        
        Optional<Like> existingLike = likeRepository.findByUserAndContent(user, content);
        
        if (existingLike.isPresent()) {
            // 取消点赞
            likeRepository.delete(existingLike.get());
            content.decrementLikeCount();
            contentRepository.save(content);
            return false;
        } else {
            // 点赞
            Like like = new Like();
            like.setUser(user);
            like.setContent(content);
            likeRepository.save(like);
            
            content.incrementLikeCount();
            contentRepository.save(content);
            return true;
        }
    }
    
    /**
     * 检查用户是否已点赞
     */
    public boolean isLiked(Long contentId, User user) {
        Content content = contentRepository.findById(contentId)
                .orElseThrow(() -> new RuntimeException("内容不存在"));
        
        return likeRepository.existsByUserAndContent(user, content);
    }
    
    /**
     * 获取内容的点赞数
     */
    public long getLikeCount(Long contentId) {
        Content content = contentRepository.findById(contentId)
                .orElseThrow(() -> new RuntimeException("内容不存在"));
        
        return likeRepository.countByContent(content);
    }
} 